module Security
  module UserAccess
    include Security::Session::Access

    def flash_message
      if flash[:notice] 
        return "<div id=\"notice\" style=\"clear:both;\">#{flash[:notice]}</div>"
      elsif flash[:error]
        return "<div id=\"error\" style=\"clear:both;\">#{flash[:error]}</div>"
      end 
    end

    def user_line
      rvalue = ""
      if user?
        rvalue = "<br/><span id=\"login_links\" style=\"color: #007a7c;\">"
        rvalue << link_to(user_name,{:controller =>"/manage/users", :action => "show_my_account"}) << " | "
        rvalue << link_to("Logout",{:controller => "/security", :action => "logout"})
        rvalue << "</span><br/>"
      end 
      rvalue
    end

    def secure_document_link(doc)
      current_version = doc.current_version
      img = doc_type_image(current_version)
      if img.length > 0
        title = "#{img} #{doc.title}"
      else
        title = doc.title
      end
      link_to(title,ca("/pages","view_document",current_version.id)).delete("\r")
    end

    def secure_links(link_array)
      rvalue = ""
      link_array.each{|link| rvalue << link << " | " if link.length > 0 }
      rvalue.strip.chop.strip
    end

    def secure_link_to(name, options = {}, html_options = nil, *params)
      if controller.access_approved?(options[:controller], options[:action], options[:id])
        return link_to(name,options,html_options,*params) 
      end
      return ""
    end

    def read_more_link(page, html_options = nil, *params)
      return "" unless page.show? &&  current_user_has_access?(page.user_group_ids)
      options = ca("/pages","show",page.id)
      return link_to("Read more...",options,html_options,*params) 
    end

    def dynamic_secure_link_to(page,html_options = nil, *params)
      return "" unless page.show? &&  current_user_has_access?(page.user_group_ids)
      options = ca("/pages","show",page.id)
      return link_to(page.title,options,html_options,*params) 
    end

    def ca(ctroller, action, id = nil)
      return {:controller => ctroller, :action => action} if id.nil?
      return {:controller => ctroller, :action => action, :id => id}
    end

    def generate_menu
      return session[:menu] if session[:menu] 
      rvalue = ""
      rvalue << "<ul id=\"menu\">"
      rvalue << home_menu_link
      rvalue << dynamic_group
      rvalue << management_group
      rvalue << login_logout
      rvalue << "</ul>"
      session[:menu] = rvalue
      session[:menu]
    end

    private

      def doc_type_image(doc)
        rvalue = ""
        case File.extname(doc.name)
        when ".doc" 
          rvalue = image_tag("word.gif")
        when ".xls"
          rvalue = image_tag("excel.gif")
        when ".pdf"
          rvalue = image_tag("adobe.gif")
        when ".zip"
          rvalue = image_tag("zip.gif")
        end
        rvalue
      end

      def home_menu_link
        rvalue = ""
        lnk = secure_link_to("The Link",ca("/home","index"))
        rvalue << "<li class=\"home\">" << lnk << "</li>" 
        return rvalue
      end

      def login_logout
        return folder_menu_link("Logout", "/security", "logout") if user?
        folder_menu_link("Login", "/security", "login")
      end

      def dynamic_group
        rvalue = ""
        FolderContent.top_level_folders do |fldr|
          next if hide_folder?(fldr)
          rvalue << dynamic_category(fldr,true)
        end 
        rvalue
      end

      def management_group
        grp = "/manage"
        rvalue = ""
        #excluded_requests = %w(manage/users/show_my_account manage/users/update_my_account)
        excluded_requests = []

        if controller.access_to_category?(grp,excluded_requests)
          rvalue << start_expand_link(grp)
          rvalue << menu_link("My Account", "/manage/users", "show_my_account")
          rvalue << user_management_group
          rvalue << permissions_management_group
          rvalue << content_management_group
          rvalue << metadata_management_group
          rvalue << end_expand_link
        end
        rvalue
      end

      def user_management_group
        rvalue = ""
        grp = "/manage/users"
        if controller.access_to_category?(grp) && can_manage_other_users?
          rvalue = start_expand_link("Users")
          rvalue << menu_link("Site Admins", grp, "list_site_admins")
          rvalue << menu_link("Site Users", grp, "list_site_users")
          rvalue << end_expand_link
        end
        rvalue
      end

      def permissions_management_group
        rvalue = ""
        grp = "/manage/permissions"
        if controller.access_to_category?(grp)
          rvalue = start_expand_link("Permissions")
          rvalue << menu_link("Roles", grp, "list_roles")
          rvalue << menu_link("User Groups", grp, "list_user_groups")
          rvalue << menu_link("Editor Groups", grp, "list_editor_groups")
          rvalue << menu_link("System Objects", grp, "list_system_objects")
          rvalue << end_expand_link
        end
        rvalue
      end

      def content_management_group
        rvalue = ""
        grp1 = "/manage/folders"
        grp2 = "/manage/pages"
        grp3 = "/manage/functions"
        grp4 = "/manage/documents"
        grp5 = "/manage/messages"
        if controller.access_in_categories?([grp1, grp2, grp3, grp4, grp5])
          rvalue = start_expand_link("Content")
          rvalue << menu_link("Reset Menu",grp1,"reset_menu")
          rvalue << menu_link("Folders",grp1,"index")
          rvalue << menu_link("Pages",grp2,"list")
          rvalue << menu_link("Functions",grp3, "list")
          rvalue << menu_link("Documents",grp4, "list")
          rvalue << menu_link("Messages",grp5, "list")
          rvalue << end_expand_link
        end
        rvalue
      end

      def metadata_management_group
        rvalue = ""
        grp = "/manage/metadata"
        if controller.access_to_category?(grp)
          rvalue = start_expand_link("Metadata")
          rvalue << menu_link("Contact Formats", grp, "contact_formats")
          rvalue << menu_link("User Addresses", grp, "user_address_types")
          rvalue << menu_link("User Contacts", grp, "user_contact_types")
          rvalue << end_expand_link
        end
        rvalue
      end

      def can_manage_other_users?
        controller.access_approved?("/manage/users", "list_site_admins") ||
          controller.access_approved?("/manage/users", "list_site_users")
      end

      def dynamic_category(fldr,top_level = false)
        rvalue = ""
        contents = FolderContent.content_for(fldr.id)
        rvalue << start_dynamic_expand_link(fldr) if contents.length > 1 && top_level
        contents.each do |content|
          if content.sub_folder
            next if hide_folder?(content.sub_folder)
            sub_contents = FolderContent.content_for(content.sub_folder.id)
            rvalue << start_dynamic_expand_link(content.sub_folder) if sub_contents.length > 1
            rvalue << dynamic_category(content.sub_folder)
            rvalue << end_expand_link if sub_contents.length > 1
          elsif content.function
            name = content.function.name
            name = content.folder.name if contents.length == 1
            rvalue << menu_link(name, content.function.ctroller, content.function.action)  
          else
            if content.page.menu_show? &&  current_user_has_access?(content.page.user_group_ids)
              name = content.page.title
              name = content.folder.name if contents.length == 1
              rvalue << menu_link(name, "/pages", "show", content.page.id)  
            end
          end
        end
        rvalue << end_expand_link if contents.length > 1 && top_level
        rvalue
      end

      def hide_folder?(fldr)
        return false if fldr.function.length > 0
        FolderContent.all_pages_for(fldr.id) do |pg|
          return false if current_user_has_access?(pg.user_group_ids) && pg.show?
        end
        true
      end

      def start_dynamic_expand_link(fldr)
        return expand_link(fldr.name)
      end

      def start_expand_link(title)
        title = category_name(title)
        return expand_link(title)
      end

      def expand_link(title)
        return <<-LINK
          <li><a href="#" class="x">#{title}...</a><ul>
        LINK
      end

      def end_expand_link
        "</ul></li>"
      end

      def folder_menu_link(label, grp, action, id = nil)
        rvalue = ""
        lnk = secure_link_to(label,ca(grp,action,id))
        if lnk.strip.length > 0
          rvalue << "<li>" << lnk << "</li>" 
        end
        return rvalue
      end

      def menu_link(label, grp, action, id = nil)
        lnk = secure_link_to(label,ca(grp,action,id))
        return "<li>" << lnk << "</li>" if lnk.strip.length > 0
        return ""
      end

      def category_name(grp)
        grp.gsub(/\//," ").strip.capitalize
      end

      def current_group_controller?(grp)
        params[:controller] =~ /^#{controller.class.format_controller(grp)}/
      end

      def current_controller?(grp)
        params[:controller] == controller.class.format_controller(grp)
      end

      def current_action?(action)
        params[:action] == action
      end

      def current_id?(id)
        return params[:id].to_i == id.to_i if params[:id]
        return false
      end

      def current_url
        "/#{params[:controller]}/#{params[:action]}"
      end
  end
end 
